package com.hnust.util;

import com.hnust.config.YamlReader;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

public class ReplaceTextWithImage {
	public static void WriteImage(Document document) throws URISyntaxException, IOException {
		TextSelection[] textSelections = new TextSelection[1];
		while(textSelections.length>0) {
			textSelections = document.findAllPattern(Pattern.compile("[1-9][0-9]*.png"));
			if(textSelections==null){
				break;
			}
			TextSelection textSelection = textSelections[0];
			DocPicture pic = new DocPicture(document);
			String picId = textSelection.getSelectedText().replace(".png","");
			int in = 0;
			TextRange range = null;
			String fileName = picId + ".png";
			InputStream file = URIInputStream.getFileInputStream("http://"+ YamlReader.instance.getValueByKey("pic.url") + ":" + YamlReader.instance.getValueByKey("pic.port") + "/pic/"+fileName);
			pic.loadImage(file);
			TextSelection selections = document.findPattern(Pattern.compile("<img.*"+fileName+".*?/>"));
			pic.setWidth(pic.getWidth());
			pic.setHeight(pic.getHeight());

			range = selections.getAsOneRange();
			in = range.getOwnerParagraph().getChildObjects().indexOf(range);
			range.getOwnerParagraph().getChildObjects().insert(in, pic);
			range.getOwnerParagraph().getChildObjects().remove(range);
		}
	}
}